<template>
  <ElForm label-position="top" :model="user">
    <ElFormItem>
      <ElInput placeholder="请输入用户名" v-model="user.userName" style="margin-bottom: 10px"></ElInput>
    </ElFormItem>
    <ElFormItem>
      <ElInput placeholder="请输入密码" show-password v-model="user.password" style="margin-bottom: 10px"></ElInput>
    </ElFormItem>
    <ElCheckbox v-model="user.remember"
                style="margin-right: 10px;font-size: 14px;float: left;width: 70px;height: 16px;" @change="rememberChange">记住密码
    </ElCheckbox>
    <span style="float: right;font-size: 14px;">
      <a href="/settings"
         style="margin-right: 10px;color: #0468FF;text-decoration: none;">忘记密码？
      </a>
    </span>
    <ElFormItem style="margin-top: 80px;">
      <ElButton  size="large" style="width: 100%;height: 40px;background-color: #0460FF;color: #FFF;" @click="login">登录</ElButton>
    </ElFormItem>
  </ElForm>
</template>

<script setup>
import { ref } from 'vue';
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";
import qs from "qs";



const user = ref({
  userName: '',
  password: '',
  remember: false
});

const login = () => {
  if (!user.value.userName || !user.value.password){
    ElMessage.error('用户名或密码不能为空')
    return;
  }
  user.value.loginType = 'username';
  axios.post(window.getBaseURL(4) + '/v1/user/login',qs.stringify(user.value))
      .then(response => {
        console.log(response.data)
        if (response.data.code === 2000){
          ElMessage.success('登录成功')
          if (user.value.remember){
            sessionStorage.setItem('token',JSON.stringify(response.data))
          }
          router.push('/statistics/duplicateStatistical')
        }else{
          ElMessage.error(response.data.msg)
          user.value.password = ''
          user.value.userName = ''
        }
      }).catch(error => {
    console.log(error)
    ElMessage.error(error.message)
    user.value.password = ''
    user.value.userName = ''});
}

const rememberChange = () => {
  if (!user.value.remember){
    sessionStorage.removeItem('token')
  }
}
</script>
